package com.carey.gae.data;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

public class OAuthDatabase {
	private static final Logger log = Logger.getLogger(OAuthDatabase.class
			.getName());

	@SuppressWarnings("unchecked")
	public static void setProperty(String consumer_key, OAuthProperties value) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		OAuthProperties op = null;
		try {
			String query = "select from " + OAuthProperties.class.getName()
					+ " where consumer_key == '" + consumer_key + "'";
			log.info("query: " + query);
			List<OAuthProperties> oAuthProperties = (List<OAuthProperties>) pm
					.newQuery(query).execute();
			if (oAuthProperties.size() > 0) {
				op = oAuthProperties.get(0);
				op.setCopy(value);
			} else {
				op = value;
			}
			pm.makePersistent(op);
		} catch (Exception e) {
			log.warning(e.getMessage());
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public static OAuthProperties getProperty(String consumer_key) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			String query = "select from " + OAuthProperties.class.getName()
					+ " where consumer_key == '" + consumer_key + "'";
			log.info("query: " + query);
			List<OAuthProperties> oAuthProperties = (List<OAuthProperties>) pm
					.newQuery(query).execute();
			if (oAuthProperties.size() > 0) {
				return oAuthProperties.get(0);
			} else {
				return null;
			}
		} catch (Exception e) {
			log.warning(e.getMessage());
			return null;
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public static OAuthProperties getPropertyByAuthorizeToken(
			String authorize_token) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			String query = "select from " + OAuthProperties.class.getName()
					+ " where authorize_token == '" + authorize_token + "'";
			log.info("query: " + query);
			List<OAuthProperties> oAuthProperties = (List<OAuthProperties>) pm
					.newQuery(query).execute();
			if (oAuthProperties.size() > 0) {
				return oAuthProperties.get(0);
			} else {
				return null;
			}
		} catch (Exception e) {
			log.warning(e.getMessage());
			return null;
		} finally {
			pm.close();
		}
	}
}
